package com.android.projectsquirrel;
import java.util.ArrayList;
import java.util.List;

import android.app.*;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;
import android.widget.AdapterView.OnItemSelectedListener;

public class NewSighting extends Activity {
	String chosenProfileName = "";
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.environment);
        String[] treeNames = new String[] {"Dont Know","Yes","No","Select One"};
        String[] dataSubmissions = new String[]{"Select One","Yes","No",};
        String[]  predators= new String[] {"Never","Low(1-2 per week)","Medium(3-4 per week)","High(5+ per week)","Select One"};
        String[] dogs = new String[] {"None","Low(1-2 per day)","Medium(3-4 per day)","High(5+ per day)","Select One"};
        String[] items = new String[] {"Single Family House or Duplex","Multiple Family Dwelling (e.g. Apartment Building)","Highrise Building","Neighborhood Park","Forest or Nature Preserve","Zoo","Arboretum or Botanical Garden","Commercial Establishment","School","College or University Campus","Vacant Lot","Cemetery","Farmland","Select One"};
        
        Spinner environment_spinner = (Spinner) findViewById(R.id.environmentSpinner);
        ArrayAdapter<String> environment_adapter = new ArrayAdapter<String>(this,
                    android.R.layout.simple_spinner_item, items);
        environment_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        environment_spinner.setAdapter(environment_adapter);
        environment_spinner.setSelection(13);
        
        final Spinner submittedData = (Spinner) findViewById(R.id.submittedData);
        ArrayAdapter<String> data_adapter1 = new ArrayAdapter<String>(this,
                    android.R.layout.simple_spinner_item, dataSubmissions);
        data_adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        submittedData.setAdapter(data_adapter1);
//        submittedData.setSelection(2);
        submittedData.setOnItemSelectedListener(new
                OnItemSelectedListener()
         {
        	public void onItemSelected(AdapterView parent, View v, int position,
                long id){
        			int pos = submittedData.getSelectedItemPosition();
        			switch (pos) {
        				case 1:
        					populateSpinnerItems();
			                break;
		               case 2:
			                break;
	               }
        	}
        	 public void onNothingSelected(AdapterView arg0) {}

           	});
        
        final Spinner usersChoiceSpinner = (Spinner) findViewById(R.id.userQuestion);
        ArrayAdapter<String> choice_adapter1 = new ArrayAdapter<String>(this,
                    android.R.layout.simple_spinner_item, new String[]{" "});
        choice_adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        usersChoiceSpinner.setAdapter(choice_adapter1);
//        usersChoiceSpinner.setSelection(2);
        usersChoiceSpinner.setOnItemSelectedListener(new
                OnItemSelectedListener()
         {
        	public void onItemSelected(AdapterView parent, View v, int position,
                long id){
        			int pos = usersChoiceSpinner.getSelectedItemPosition();
        			switch (pos) {
        				case 1:
        					populate();
			                break;
		               case 2:
			                break;
	               }
        	}
        	 public void onNothingSelected(AdapterView arg0) {}

           	});

        Button next = (Button) findViewById(R.id.identifyTreeButton);
        next.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
            	Intent myIntent = new Intent(view.getContext(), TreeInfo.class);
                startActivity(myIntent);
            }
        });
        
        EditText editLatitude = (EditText)findViewById(R.id.latitudeEditText);
        String lat = Double.toString(GPSHelper.latitude);
        editLatitude.setText(lat);
        editLatitude.setEnabled(false);
        
        EditText editLongitude = (EditText)findViewById(R.id.longitudeEditText);
        String longitude = Double.toString(GPSHelper.longitude);
        editLongitude.setText(longitude);
        editLongitude.setEnabled(false);
        
        Spinner treeSpinner1 = (Spinner) findViewById(R.id.nutSpinner);
        ArrayAdapter<String> tree_adapter1 = new ArrayAdapter<String>(this,
                    android.R.layout.simple_spinner_item, treeNames);
        tree_adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        treeSpinner1.setAdapter(tree_adapter1);
        treeSpinner1.setSelection(3);
        
        Spinner treeSpinner2 = (Spinner) findViewById(R.id.seedSpinner);
        ArrayAdapter<String> tree_adapter2 = new ArrayAdapter<String>(this,
                    android.R.layout.simple_spinner_item, treeNames);
        tree_adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        treeSpinner2.setAdapter(tree_adapter2);
        treeSpinner2.setSelection(3);

        Spinner treeSpinner3 = (Spinner) findViewById(R.id.fruitSpinner);
        ArrayAdapter<String> tree_adapter3 = new ArrayAdapter<String>(this,
                    android.R.layout.simple_spinner_item, treeNames);
        tree_adapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        treeSpinner3.setAdapter(tree_adapter3);
        treeSpinner3.setSelection(3);
        
        Spinner treeSpinner4 = (Spinner) findViewById(R.id.tinySpinner);
        ArrayAdapter<String> tree_adapter4 = new ArrayAdapter<String>(this,
                    android.R.layout.simple_spinner_item, treeNames);
        tree_adapter4.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        treeSpinner4.setAdapter(tree_adapter4);
        treeSpinner4.setSelection(3);
        
        Spinner treeSpinner5 = (Spinner) findViewById(R.id.coniferousSpinner);
        ArrayAdapter<String> tree_adapter5 = new ArrayAdapter<String>(this,
                    android.R.layout.simple_spinner_item, treeNames);
        tree_adapter5.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        treeSpinner5.setAdapter(tree_adapter5);
        treeSpinner5.setSelection(3);
        
        Spinner dogSpinner1 = (Spinner) findViewById(R.id.dogSpinner);
        ArrayAdapter<String> dog_adapter = new ArrayAdapter<String>(this,
                    android.R.layout.simple_spinner_item, dogs);
        dog_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        dogSpinner1.setAdapter(dog_adapter);
        dogSpinner1.setSelection(4);
        
        Spinner catSpinner = (Spinner) findViewById(R.id.catSpinner);
        ArrayAdapter<String> cat_adapter = new ArrayAdapter<String>(this,
                    android.R.layout.simple_spinner_item, dogs);
        cat_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        catSpinner.setAdapter(cat_adapter);
        catSpinner.setSelection(4);

        Spinner coyoteSpinner = (Spinner) findViewById(R.id.coyoteSpinner);
        ArrayAdapter<String> coyote_adapter = new ArrayAdapter<String>(this,
                    android.R.layout.simple_spinner_item,predators);
        coyote_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        coyoteSpinner.setAdapter(coyote_adapter);
        coyoteSpinner.setSelection(4);
        
        Spinner hawksSpinner = (Spinner) findViewById(R.id.hawksSpinner);
        ArrayAdapter<String> hawks_adapter = new ArrayAdapter<String>(this,
                    android.R.layout.simple_spinner_item, predators);
        hawks_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        hawksSpinner.setAdapter(hawks_adapter);
        hawksSpinner.setSelection(4);
        
        Spinner poisonedGrainSpinner = (Spinner) findViewById(R.id.grainSpinner);
        ArrayAdapter<String> grain_adapter = new ArrayAdapter<String>(this,
                    android.R.layout.simple_spinner_item, predators);
        grain_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        poisonedGrainSpinner.setAdapter(grain_adapter);
        poisonedGrainSpinner.setSelection(4);
        
        Button continueButton = (Button) findViewById(R.id.squirrelInfo);
        continueButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
//            	populate();
            	Boolean okToProceed = checkForErrors();
            	EditText profileName = (EditText)findViewById(R.id.profileName);
            	String name = profileName.getText().toString();
            	if(okToProceed){
            		if(chosenProfileName.equals(name)){
            			update(chosenProfileName);
            		}
            		else{
            			insertData();
            		}
            		
	            	Intent myIntent = new Intent(view.getContext(), survey_part2.class);
	            	myIntent.putExtra("profilename",name);
	                startActivity(myIntent);
            	}
//            	displayData();
            }
        });
        
	}
	
	public Boolean checkForErrors(){
		Boolean ok = true;
		String questionNumbers = "Please answer the following survey questions: \n";
		Spinner checkSubmittedData = (Spinner) findViewById(R.id.submittedData);
		if(checkSubmittedData.getSelectedItemPosition()== 0){
			questionNumbers = questionNumbers.concat("Question 1.Submitted data before for this site?\n");
			ok = false;
			
		}
		EditText checkProfileName = (EditText) findViewById(R.id.profileName);
		if((checkProfileName.getText().toString()).equals("")){
			questionNumbers = questionNumbers.concat("Question 3.Please enter a valid profile name.\n");
			ok = false;
			
		}
		
		
		Spinner checkSquirrelEnvironment = (Spinner) findViewById(R.id.environmentSpinner);
		if(checkSquirrelEnvironment.getSelectedItemPosition()== 13){
			questionNumbers = questionNumbers.concat("Question 7. Please select a squirrel environment.\n");
			ok = false;
			
		}
		Spinner checkNutBearing = (Spinner) findViewById(R.id.nutSpinner);
		if(checkNutBearing.getSelectedItemPosition()== 3){
			questionNumbers = questionNumbers.concat("Question 7. Please select a valid response for nut bearing trees.\n");
			ok = false;
			
		}
		Spinner checkSeedBearing = (Spinner) findViewById(R.id.seedSpinner);
		if(checkSeedBearing.getSelectedItemPosition()== 3){
			questionNumbers = questionNumbers.concat("Question 7. Please select a valid response for seed bearing trees.\n");
			ok = false;
			
		}
		Spinner checkFruitBearing = (Spinner) findViewById(R.id.fruitSpinner);
		if(checkFruitBearing.getSelectedItemPosition()== 3){
			questionNumbers = questionNumbers.concat("Question 7. Please select a valid response for fruit bearing trees.\n");
			ok = false;
			
		}
		Spinner checkTinySeeded = (Spinner) findViewById(R.id.tinySpinner);
		if(checkTinySeeded.getSelectedItemPosition()== 3){
			questionNumbers = questionNumbers.concat("Question 7. Please select a valid response for tiny seeded trees.\n");
			ok = false;
			
		}
		
		Spinner checkConiferous = (Spinner) findViewById(R.id.coniferousSpinner);
		if(checkConiferous.getSelectedItemPosition()== 3){
			questionNumbers = questionNumbers.concat("Question 7. Please select a valid response for coniferous trees.\n");
			ok = false;
			
		}
		Spinner checkDogs = (Spinner) findViewById(R.id.dogSpinner);
		if(checkDogs.getSelectedItemPosition()== 4){
			questionNumbers = questionNumbers.concat("Question 8. Please select a valid response for dogs near the site.\n");
			ok = false;
			
		}
		Spinner checkCats = (Spinner) findViewById(R.id.catSpinner);
		if(checkCats.getSelectedItemPosition()== 4){
			questionNumbers = questionNumbers.concat("Question 8. Please select a valid response for cats near the site.\n");
			ok = false;
			
		}
		
		Spinner checkCoyotes = (Spinner) findViewById(R.id.coyoteSpinner);
		if(checkCoyotes.getSelectedItemPosition()== 4){
			questionNumbers = questionNumbers.concat("Question 9. Please select a valid response for coyotes near the site.\n");
			ok = false;
			
		}
		Spinner checkHawks = (Spinner) findViewById(R.id.hawksSpinner);
		if(checkHawks.getSelectedItemPosition()== 4){
			questionNumbers = questionNumbers.concat("Question 9. Please select a valid response for hawks near the site.\n");
			ok = false;
			
		}
		Spinner checkGrain = (Spinner) findViewById(R.id.grainSpinner);
		if(checkGrain.getSelectedItemPosition()== 4){
			questionNumbers = questionNumbers.concat("Question 9. Please select a valid response for Poisoned Grain near the site.\n");
			ok = false;
			
		}
		
		if(ok == false){
			showAlert(questionNumbers);
		}
		return ok;
	}
	
	public void showAlert(String str){
		 // prepare the alert box
        AlertDialog.Builder alertbox = new AlertDialog.Builder(this);

        // set the message to display
        alertbox.setMessage(str);

        // add a neutral button to the alert box and assign a click listener
        alertbox.setNegativeButton("Ok", new DialogInterface.OnClickListener() {

            // click listener on the alert box
            public void onClick(DialogInterface arg0, int arg1) {
            }
        });

        // show it
        alertbox.show();
	}
	
	public void populateSpinnerItems(){
		final Spinner usersChoiceSpinner = (Spinner) findViewById(R.id.userQuestion);
		final List<String> items = new ArrayList<String>();
		items.add(" ");
		items.addAll(displayData());
        ArrayAdapter<String> choice_adapter1 = new ArrayAdapter<String>(this,
                    android.R.layout.simple_spinner_item, items);
        choice_adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        usersChoiceSpinner.setAdapter(choice_adapter1);
//        usersChoiceSpinner.setSelection(2);
        usersChoiceSpinner.setOnItemSelectedListener(new
                OnItemSelectedListener()
         {
        	public void onItemSelected(AdapterView parent, View v, int position,
                long id){
        			int pos = usersChoiceSpinner.getSelectedItemPosition();
        			chosenProfileName = items.get(pos);
        			populateFields(chosenProfileName);
        	}
        	 public void onNothingSelected(AdapterView arg0) {}

           	});
	}
	
	
	
	 public void show(String s){
   	  Toast toast1 = Toast.makeText(this, s, Toast.LENGTH_LONG);
   	  toast1.show();
     }
	
	public void OnResume(){
		super.onResume();
		DBAdapter db = new DBAdapter(this);
		db.open();
	}
	
	public void onPause(){
		super.onPause();
		DBAdapter db = new DBAdapter(this);
		db.close();
	}
	
	public void populate(){
		Spinner submittedBeforeSpinner = (Spinner)findViewById(R.id.submittedData);
		String submitted = submittedBeforeSpinner.getSelectedItem().toString();
		if(submitted.equals("Yes")){
			EditText editProfile = (EditText)findViewById(R.id.profileName);
			String profile = editProfile.getText().toString();
			populateFields(profile);
			
			
		}
	}
	
	public void populateFields(String profile){
		DBAdapter db = new DBAdapter(this);
		CharSequence text;
		int i;
		db.open();
		Cursor c = db.getTitle(profile);
    	startManagingCursor(c);
    	if(c.moveToFirst()){
    		
    		EditText profileName = (EditText)findViewById(R.id.profileName);
    		EditText latitude = (EditText)findViewById(R.id.latitudeEditText);
    		EditText longitude = (EditText)findViewById(R.id.longitudeEditText);
    		Spinner nutSpinner = (Spinner)findViewById(R.id.nutSpinner);
        	Spinner seedSpinner = (Spinner)findViewById(R.id.seedSpinner);
        	Spinner fruitSpinner = (Spinner)findViewById(R.id.fruitSpinner);
        	Spinner tinySpinner = (Spinner)findViewById(R.id.tinySpinner);
        	Spinner coniferousSpinner = (Spinner)findViewById(R.id.coniferousSpinner);
        	EditText otherSpinner = (EditText)findViewById(R.id.otherTrees);
        	Spinner dogSpinner = (Spinner)findViewById(R.id.dogSpinner);
        	Spinner catSpinner = (Spinner)findViewById(R.id.catSpinner);
        	Spinner coyoteSpinner = (Spinner)findViewById(R.id.coyoteSpinner);
        	Spinner hawksSpinner = (Spinner)findViewById(R.id.hawksSpinner);
        	Spinner grainSpinner = (Spinner)findViewById(R.id.grainSpinner);
        	
        	Spinner settingSpinner = (Spinner)findViewById(R.id.environmentSpinner);
        	text = c.getString(0);
        	profileName.setText(text);
    		text = c.getString(2);
    		latitude.setText(text);
    		text = c.getString(3);
    		longitude.setText(text);
    		i = Integer.parseInt(c.getString(4));
    		settingSpinner.setSelection(i);
    		i = Integer.parseInt(c.getString(5));
    		nutSpinner.setSelection(i);
    		i = Integer.parseInt(c.getString(6));
    		seedSpinner.setSelection(i);
    		i = Integer.parseInt(c.getString(7));
    		fruitSpinner.setSelection(i);
    		i = Integer.parseInt(c.getString(8));
    		tinySpinner.setSelection(i);
    		i = Integer.parseInt(c.getString(9));
    		coniferousSpinner.setSelection(i);
    		text = c.getString(10);
    		otherSpinner.setText(text);
    		i = Integer.parseInt(c.getString(11));
    		dogSpinner.setSelection(i);
    		i = Integer.parseInt(c.getString(12));
    		catSpinner.setSelection(i);
    		i = Integer.parseInt(c.getString(13));
    		coyoteSpinner.setSelection(i);
    		i = Integer.parseInt(c.getString(14));
    		hawksSpinner.setSelection(i);
    		i = Integer.parseInt(c.getString(15));
    		grainSpinner.setSelection(i);
    	}
		c.close();
		db.close();
		
		
	}
	public void insertData(){
    	DBAdapter db = new DBAdapter(this);
    	EditText editProfile = (EditText)findViewById(R.id.profileName);
    	Spinner submittedBeforeSpinner = (Spinner)findViewById(R.id.submittedData);
    	EditText editLatitude = (EditText)findViewById(R.id.latitudeEditText);
    	EditText editLongitude = (EditText)findViewById(R.id.longitudeEditText);
    	Spinner nutSpinner = (Spinner)findViewById(R.id.nutSpinner);
    	Spinner seedSpinner = (Spinner)findViewById(R.id.seedSpinner);
    	Spinner fruitSpinner = (Spinner)findViewById(R.id.fruitSpinner);
    	Spinner tinySpinner = (Spinner)findViewById(R.id.tinySpinner);
    	Spinner coniferousSpinner = (Spinner)findViewById(R.id.coniferousSpinner);
    	EditText otherSpinner = (EditText)findViewById(R.id.otherTrees);
    	Spinner dogSpinner = (Spinner)findViewById(R.id.dogSpinner);
    	Spinner catSpinner = (Spinner)findViewById(R.id.catSpinner);
    	Spinner coyoteSpinner = (Spinner)findViewById(R.id.coyoteSpinner);
    	Spinner hawksSpinner = (Spinner)findViewById(R.id.hawksSpinner);
    	Spinner grainSpinner = (Spinner)findViewById(R.id.grainSpinner);
    	
    	Spinner settingSpinner = (Spinner)findViewById(R.id.environmentSpinner);
		 db.open();
		 Boolean id;
		 long ins;
		 	ins = db.insertTitle(editProfile.getText().toString(),
	        		submittedBeforeSpinner.getSelectedItemPosition(),
	        		editLatitude.getText().toString(),
	        		editLongitude.getText().toString(),
	        		settingSpinner.getSelectedItemPosition(),
	        		nutSpinner.getSelectedItemPosition(),
	        		seedSpinner.getSelectedItemPosition(),
	        		fruitSpinner.getSelectedItemPosition(),
	        		tinySpinner.getSelectedItemPosition(),
	        		coniferousSpinner.getSelectedItemPosition(),
	        		otherSpinner.getText().toString(),
	        		dogSpinner.getSelectedItemPosition(),
	        		catSpinner.getSelectedItemPosition(),
	        		coyoteSpinner.getSelectedItemPosition(),
	        		hawksSpinner.getSelectedItemPosition(),
	        		grainSpinner.getSelectedItemPosition()
	        		);
	        		        
//	        
	        db.close();
	}
	

	
	public void update(String name){
		DBAdapter db = new DBAdapter(this);
		EditText editProfile = (EditText)findViewById(R.id.profileName);
    	Spinner submittedBeforeSpinner = (Spinner)findViewById(R.id.submittedData);
    	EditText editLatitude = (EditText)findViewById(R.id.latitudeEditText);
    	EditText editLongitude = (EditText)findViewById(R.id.longitudeEditText);
    	Spinner settingSpinner = (Spinner)findViewById(R.id.environmentSpinner);
    	Spinner nutSpinner = (Spinner)findViewById(R.id.nutSpinner);
    	Spinner seedSpinner = (Spinner)findViewById(R.id.seedSpinner);
    	Spinner fruitSpinner = (Spinner)findViewById(R.id.fruitSpinner);
    	Spinner tinySpinner = (Spinner)findViewById(R.id.tinySpinner);
    	Spinner coniferousSpinner = (Spinner)findViewById(R.id.coniferousSpinner);
    	EditText otherSpinner = (EditText)findViewById(R.id.otherTrees);
    	Spinner dogSpinner = (Spinner)findViewById(R.id.dogSpinner);
    	Spinner catSpinner = (Spinner)findViewById(R.id.catSpinner);
    	Spinner coyoteSpinner = (Spinner)findViewById(R.id.coyoteSpinner);
    	Spinner hawksSpinner = (Spinner)findViewById(R.id.hawksSpinner);
    	Spinner grainSpinner = (Spinner)findViewById(R.id.grainSpinner);
    	 db.open();
		 Boolean id;
		 long ins;
    	
		id = db.updateTitle(
				editProfile.getText().toString(),
        		submittedBeforeSpinner.getSelectedItemPosition(),
        		editLatitude.getText().toString(),
        		editLongitude.getText().toString(),
        		settingSpinner.getSelectedItemPosition(),
        		nutSpinner.getSelectedItemPosition(),
        		seedSpinner.getSelectedItemPosition(),
        		fruitSpinner.getSelectedItemPosition(),
        		tinySpinner.getSelectedItemPosition(),
        		coniferousSpinner.getSelectedItemPosition(),
        		otherSpinner.getText().toString(),
        		dogSpinner.getSelectedItemPosition(),
        		catSpinner.getSelectedItemPosition(),
        		coyoteSpinner.getSelectedItemPosition(),
        		hawksSpinner.getSelectedItemPosition(),
        		grainSpinner.getSelectedItemPosition());
		db.close();

		
	}
	 public List<String> displayData(){
    	Context context = getApplicationContext();
    	List<String> profiles = new ArrayList<String>();
    	DBAdapter db = new DBAdapter(this);
    	db.open();
    	Cursor c = db.getAllTitles();
    	startManagingCursor(c);
    	if(c.moveToFirst()){
//    	if(c!=null){
//    		c.moveToNext();
//    		if(c.getColumnCount()!=0){
    			 while (c.isAfterLast() == false) {
//    				 EditText edit = (EditText)findViewById(R.id.profileName);
    				 profiles.add(c.getString(0));
//    	    			Toast toast1 = Toast.makeText(context, text, Toast.LENGTH_LONG);
//    	    			toast1.show();
    		       	    c.moveToNext();
    		        }

    	}
    	else {
    		Toast toast = Toast.makeText(context, "There are no saved profiles", Toast.LENGTH_LONG);
			toast.show();	
    	}
    	c.close();
    	db.close();
    	return profiles;
    }
	
	 
	 public boolean onCreateOptionsMenu(Menu menu) {
	        boolean supRetVal = super.onCreateOptionsMenu(menu);
	        menu.add(Menu.NONE, 0, Menu.NONE, "Go Home");
	    	//.setIcon(android.R.drawable.);
		return supRetVal;
	}
	
	
	public boolean onOptionsItemSelected(MenuItem item) {
	    switch (item.getItemId()) {
	        case 0:
	        	startActivity(new Intent(NewSighting.this, Main.class));
	            return true;
	    }
	    return false;
	}

}
